package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {


    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(
                        request -> request
//                                .requestMatchers("/api/login/**", "/api/auth/login", "/api/annotation/**").permitAll()//登陆请求可以不用验证
//                                .requestMatchers("/api/users/**").hasAnyRole("admin") // 用户列表可以不用验证
//                                .requestMatchers("/api/products/**").hasAnyRole("admin", "guest", "visitor")
//                                .anyRequest()
                                .anyRequest().permitAll() // 其他请求需要验证
                )
                .csrf((csrf) -> csrf.disable())
                .formLogin(Customizer.withDefaults())
                .httpBasic(Customizer.withDefaults())
                .logout(Customizer.withDefaults());
        return http
                .build();
    }

    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("sales1").password(new BCryptPasswordEncoder().encode("sales1")).roles("sales");
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        UserDetails user1 = User.
                withUsername("admin")
                .password(new BCryptPasswordEncoder().encode("admin")).roles("admin").build();
        UserDetails user2 = User.
                withUsername("guest")
                .password(new BCryptPasswordEncoder().encode("guest")).roles("guest").build();
        UserDetails user3= User.
                withUsername("visitor")
                .password(new BCryptPasswordEncoder().encode("visitor")).roles("visitor").build();
        return new InMemoryUserDetailsManager(user1, user2, user3);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
